package com.dsteiner.gwt.cafeteriasophia.client.controller;

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.dsteiner.gwt.cafeteriasophia.client.domain.Change;
import com.dsteiner.gwt.cafeteriasophia.client.domain.Product;
import com.dsteiner.gwt.cafeteriasophia.client.domain.Purchase;
import com.dsteiner.gwt.cafeteriasophia.client.domain.Sale;
import com.dsteiner.gwt.cafeteriasophia.client.domain.ShiftChange;
import com.dsteiner.gwt.cafeteriasophia.client.domain.Stock;
import com.dsteiner.gwt.cafeteriasophia.client.event.NavEvent;
import com.dsteiner.gwt.cafeteriasophia.client.model.HistoryModel;
import com.dsteiner.gwt.cafeteriasophia.client.model.NavModel;
import com.dsteiner.gwt.cafeteriasophia.client.model.ShiftChangeInfoModel;
import com.dsteiner.gwt.cafeteriasophia.client.model.ShiftChangeModel;
import com.dsteiner.gwt.cafeteriasophia.client.rpc.DataService;
import com.dsteiner.widgets.client.DateUtilImpl;
import com.dsteiner.widgets.client.JsUtil;
import com.dsteiner.widgets.client.StringUtil;
import com.dsteiner.widgets.client.Widgets.IButton;
import com.dsteiner.widgets.client.Widgets.IHTML;
import com.dsteiner.widgets.client.Widgets.ILazyWidget;
import com.dsteiner.widgets.client.Widgets.IWidget;
import com.dsteiner.widgets.client.Widgets.WidgetListenerAdapter;
import com.dsteiner.widgets.client.controller.PopupOverlayController;
import com.dsteiner.widgets.client.event.EventManagerImpl;
import com.dsteiner.widgets.client.model.PopupOverlayModel;
import com.dsteiner.widgets.client.rpc.CrudResult;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;

public class ShiftChangeInfoController {

	private ShiftChangeInfoModel shiftChangeInfoModel;
	private IHTML infoHtml;
	private HistoryModel historyModel;
	private PopupOverlayModel shiftChangeEditPopupOverlayModel;
	private ShiftChangeModel shiftChangeModel;

	public void registerShiftChangeInfoWidget(ILazyWidget shiftChangeInfoWidget) {
		shiftChangeInfoWidget.addWidgetListener(new WidgetListenerAdapter() {
			@Override
			public void onAttach(IWidget widget) {
				updateInfoHtml();
			}
		});
	}

	private void updateInfoHtml() {
		ShiftChange shiftChange = shiftChangeInfoModel.getShiftChange();
		StringBuffer html = new StringBuffer();
		
		html.append("<br><strong>Fecha: ").append(DateUtilImpl.getInstance().formatDateSpanish(shiftChange.getDate())).append("</strong><br>");
		html.append("<strong>Encargada: ").append(shiftChange.getEmployee()).append("</strong><br>");
		for (int i = 0; i < Product.products.length; i++) {
			Product product = Product.products[i];
			Stock stock = shiftChange.getStock(product);
			List<Purchase> purchases = shiftChange.getPurchases(product);
			List<Sale> sales = shiftChange.getSales(product);
			if(shiftChange.getStockSum(product) > 0 || shiftChange.getPurchasesSum(product) > 0 
					|| shiftChange.getSalesSum(product) > 0){
				html.append("<strong>").append(product.getName()).append("</strong><br>");
				if(shiftChange.getStockSum(product) > 0){
					addStock(html, stock);
					html.append("<br>");
				}
				if(shiftChange.getSalesSum(product) > 0){
					addSales(html, sales);
					html.append("<br>");
				}
				if(shiftChange.getPurchasesSum(product) > 0){
					addPurchases(html, purchases);
					html.append("<br>");
				}
			}
		}
		ShiftChange lastShiftChange = historyModel.getLastShiftChange(shiftChange);
		if(lastShiftChange != null){
			StringBuffer sb = new StringBuffer();
			List<Change> changes = new ArrayList<Change>();
			double totalValueChange = ShiftChangeEditController.getTotalValueChange(shiftChange, lastShiftChange, sb, changes);
			html.append("<strong>cambio de turno con variacion de Q"+totalValueChange+"</strong><br>").append(sb.toString());
//			if(totalValueChange < 0){
//			}
		}
		infoHtml.setHTML(html.toString());
	}

	public static void addStock(StringBuffer html, Stock stock) {
		html.append("<span style=\"font-style:italic;\">Inventario:</span> ").append((int)Math.round(stock.getAmount()));
	}

	public static void addSales(StringBuffer html, List<Sale> sales) {
		html.append("<span style=\"font-style:italic;\">Ventas:</span> ");
		for (Sale sale : sales) {
			if(sale.getAmount() == 0)
				continue;
			html.append((int)sale.getAmount()).append(" a Q ").append(sale.getPrice()).append(" ");
		}
	}

	public static void addPurchases(StringBuffer sb, List<Purchase> purchases) {
		sb.append("<span style=\"font-style:italic;\">Compras:</span> ");
		for (Purchase purchase : purchases) {
			if(purchase.getAmount() == 0)
				continue;
			sb.append(purchase.getAmount());
			if(purchase.getPrice() > 0)
				sb.append(" a Q ").append(purchase.getPrice());
			else
				sb.append(" Q");
			sb.append(" ");
		}
	}

	public void registerShiftChangeInfoModel(ShiftChangeInfoModel shiftChangeInfoModel) {
		this.shiftChangeInfoModel = shiftChangeInfoModel;
		shiftChangeInfoModel.addPropertyChangeListener("shiftChange", new PropertyChangeListener(){
			public void propertyChange(PropertyChangeEvent evt) {
				updateInfoHtml();
			}
		});
	}

	public void registerInfoHtml(IHTML infoHtml) {
		this.infoHtml = infoHtml;
	}

	public void registerHistoryModel(HistoryModel historyModel) {
		this.historyModel = historyModel;
	}

	public void registerEditLink(IHTML editLink) {
		editLink.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				PopupOverlayController.showAtCenter(shiftChangeEditPopupOverlayModel);
				shiftChangeModel.setShiftChange(shiftChangeInfoModel.getShiftChange());
			}
		});
	}

	public void registerShiftChangeEditPopupOverlayModel(PopupOverlayModel shiftChangeEditPopupOverlayModel) {
		this.shiftChangeEditPopupOverlayModel = shiftChangeEditPopupOverlayModel;
	}

	public void registerShiftChangeModel(ShiftChangeModel shiftChangeModel) {
		this.shiftChangeModel = shiftChangeModel;
	}

	public void registerUpdateShiftChangeButton(IButton updateShiftChangeButton) {
		updateShiftChangeButton.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				shiftChangeEditPopupOverlayModel.setVisible(false);
				ShiftChange shiftChange = shiftChangeModel.getShiftChange();
				shiftChange.setEditDate(new Date());
				DataService.Util.getInstance().updateObject(shiftChange, new AsyncCallback<CrudResult<ShiftChange>>(){
					public void onFailure(Throwable caught) {
						caught.printStackTrace();
					}
					public void onSuccess(CrudResult<ShiftChange> result) {
						if(!StringUtil.isEmpty(result.getError()))
							JsUtil.getInstance().showAlert("Occurio un error:\n"+result.getError());
						else{
							JsUtil.getInstance().showAlert("Cambio de turno cambiado exitosamente");
							EventManagerImpl.getInstance().fireEvent(new NavEvent(NavModel.PAGE_ID_NAV));
						}
							
					}
				});
			}
		});
	}
}